#!/usr/bin/env python
import commands
import logging
import os
import re
import subprocess

if "UBIQIS_CACHE_DIR" in os.environ:
    cache_dir = os.environ["UBIQIS_CACHE_DIR"]
else:
    import uroot.config
    cache_dir = uroot.config.CACHE_DIR

def get_platform():
    return os.uname()[0]

def next_piece(n, s):
    g = re.match(r'\b\d+', s[n:])
    if g:
        cnt = int(g.group(0))
        pat = "." * cnt
        nn = n + len(g.group(0))
        g2 = re.match(pat, s[nn:])
        if g2:
            return (nn+cnt, g2.group(0))
    return (-1, None)

def get_pieces(s):
    pieces = []
    off = 0
    while True:
        off, piece = next_piece(off, s)
        if off < 0:
            break
        pieces.append(piece)
    return pieces

def get_ubiq_lib(s):
    mm = re.search(r'(\w) _?_ZN(\w+)', s)
    if not mm:
        return (False, None)
    p = get_pieces(mm.group(2))
    for n in range(len(p)):
        g = re.match(r'^ubiq(\d+)$', p[n])
        if g:
            cnt = int(g.group(1))
            d = False
            tlib = mm.group(1)
            for tlib in "DTB":
                d = True
            if get_platform() == 'Darwin':
                return (d,os.path.join(os.environ['UBIQIS_ROOT'],'lib%s-gcc.dylib' % '-'.join(p[0:n + cnt + 1])))
            else:
                return (d,os.path.join(os.environ['UBIQIS_ROOT'],'lib%s-gcc.so' % '-'.join(p[0:n + cnt + 1])))
    return (False, None)

def getubi(s):
    pieces = re.compile(r'[-/\\]').split(s)
    for i in xrange(len(pieces)):
        p = pieces[i]
        g = re.compile(r'^ubiq(\d+)$').match(p)
        if g:
            ret = '-'.join(pieces[i:i+int(g.group(1))+1])
            return ret
    return None

def get_ubiq_libs_from_nm(nm_list):
    curr = getubi(os.getcwd())
    nmed = set()
    libs = set()
    while len(nm_list)>0:
        new_nm_list = []
        nm_out = subprocess.Popen(build_command_line(['nm'] + nm_list),
                                  shell=True, stdout=subprocess.PIPE).stdout
        for line in nm_out:
            (tlib, lib) = get_ubiq_lib(line)
            if tlib:
                if lib in libs:
                    continue
                libs.add(lib)
                if lib not in nmed:
                    if curr != getubi(lib):
                        new_nm_list.append(lib)
                    nmed.add(lib)
        nm_list = new_nm_list
    return libs

def build_command_line(args):
    cmd = ' '.join(arg for arg in args)
    print cmd
    return cmd
